package com.zenithsun.common.security.sql;

import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * SQL注入处理
 * 
 */
public class SqlInjectionManager {
	
	private static Logger log = LoggerFactory.getLogger(SqlInjectionManager.class);
	//SQL Injection  验证是否SQL盲注
	
	private static final String SQL_INJECTION_VALIDATE_EXPRESSION="(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|"  
            + "(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)";
	/**
	 * 验证是否存在SQL关键字、符号等
	 * @param sqlParam
	 * @return
	 */
	public static boolean isInjection(String sqlParam){
		if(!StringUtils.isEmpty(sqlParam))
		{
			log.info("SQL:注入验证");
			return getPattern(SQL_INJECTION_VALIDATE_EXPRESSION).matcher(sqlParam.toLowerCase()).find();
		}
		return false;
	}
	/**
	 * 正则
	 * @param reg
	 * @return
	 */
	private static Pattern getPattern(String reg){
		Pattern pattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);
		return pattern;
	}
	/**
	 * 验证是否存在SQL关键字、符号等，如有抛出异常
	 * @param sqlParam
	 * @throws SQLClientInfoException
	 */
	public static void validateSqlParam(String sqlParam) throws SqlInjectionException{
		//TODO 验证并抛出异常
		if(isInjection(sqlParam)){
			throw new SqlInjectionException();
		}
	}
	/**
	 * 验证是否存在SQL关键字、符号等，如有抛出异常
	 * @param sqlParam[]
	 * @throws SQLClientInfoException
	 */
	public static void validateSqlParam(String[] sqlParam) throws SqlInjectionException{
		//TODO 验证并抛出异常
		for (int i = 0; i < sqlParam.length; i++) {
			if(isInjection(sqlParam[0])){
				throw new SqlInjectionException();
			}
		}
		
	}
}
